package javax.servlet.http;

import com.wangwei.modules.utils.HttpResponseUtil
import java.io.BufferedOutputStream
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.PrintWriter
import javax.servlet.Servlet
import javax.servlet.ServletConfig
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import java.io.IOException
import com.wangwei.modules.utils.StreamUtil

open class HttpServletRequest(var method: String, var url: String, var http: String, var header: HashMap<String, String>, var paremeters: HashMap<String, String>) : ServletRequest {

	constructor () :
			this("", "", "", HashMap<String, String>(), hashMapOf<String, String>()) {
	}

	constructor(inputStream: InputStream?) :
			this("", "", "", HashMap<String, String>(), hashMapOf<String, String>()) {

		this.inputStream = inputStream;
		if (inputStream != null) {
			init()
		}


	}

	var inputStream: InputStream? = null


	fun init() {
		var configString: String = StreamUtil.inputStream2String(inputStream)
		var configs = configString.split('\n')

		for ((index, config) in configs.withIndex()) {
			if ("".equals(config.trim())) {
				continue
			}
			if (config.contains(":")) {
				var temp = config.split(":")
				addHeader(temp[0], temp[1])
			} else if (config.contains("=")&&index>0) {
				anaParam(config)
			} else if (index==0) {
				var temp = config.split(" ")
				if (temp.size == 3) {
					method = temp[0]
					http = temp[2]
					anaParam(temp[1])
				}
			}
		}

	}


	override fun getParameter(name: String): String? = paremeters[name]

	override fun getParameterMap(): HashMap<String, Array<String>> {
		var p = hashMapOf<String, Array<String>>()
		for ((k, v) in paremeters) {
			p.put(k, arrayOf<String>(v))
		}
		return p
	}

	/**
	 *url的后缀
	 */
	fun getSuffix(): String? {
		var index = url.lastIndexOf(".");
		if (index == -1)
			return null
		return url.substring(index)
	}

	fun addHeader(key: String, value: String) {
		header.put(key, value)
	}


	fun anaParam(url: String) {
		/*
         *问号判断是否有url
         */
		var index = url.indexOf("?")
		var hasEqual = url.contains("=")
		if (index == -1 && !hasEqual) { //无?无=
			this.url = url;
		} else if (index == -1) {//无?有=
			var paras = url.split("&")
			for (para in paras) {
				var kv = para.split("=")
				paremeters.put(kv[0], kv[1])
			}
		} else if (!hasEqual) {//无=有?
			this.url = url.substring(0, index);
		} else {//有=有?
			this.url = url.substring(0, index);
			var paraString = url.substring(index + 1)
			var paras = paraString.split("&")
			for (para in paras) {
				var kv = para.split("=")
				paremeters.put(kv[0], kv[1])
			}
		}


	}


	fun convertStreamToString(ism: InputStream): String {

		var reader = BufferedReader(InputStreamReader(ism));
		var sb = StringBuilder();
		var line: String? = null;
		try {
			line = reader.readLine()
			while (line != null) {
				sb.append(line + "/n");
				line = reader.readLine()
			}

		} catch (e: IOException) {
			e.printStackTrace();
		} finally {
			try {
				ism.close();
			} catch (e: IOException) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}


	override fun toString() = "$method $url [$paremeters]"

}

open class HttpServletResponse(var outputStream: OutputStream?) : ServletResponse {
	constructor () : this(null)


	companion object {
		val SC_BAD_REQUEST = 400;

		val SC_NOT_FOUND = 404;

		val SC_METHOD_NOT_ALLOWED = 405;
	}


	override fun getOutputStream(): BufferedOutputStream {
		return BufferedOutputStream(outputStream)
	}

	fun getWriter(): PrintWriter {
		return PrintWriter(outputStream)
	}

	fun sendError(code: Int, message: String) {
		var printWriter = getOutputStream()
		var a = HttpResponseUtil.getCodeMessageReturn(code, message)
		printWriter.write(a, 0, a.size)
		printWriter.close()
	}


}


abstract class HttpServlet : Servlet {
	constructor() : super()

	companion object {
		val METHOD_DELETE = "DELETE";
		val METHOD_HEAD = "HEAD";
		val METHOD_GET = "GET";
		val METHOD_OPTIONS = "OPTIONS";
		val METHOD_POST = "POST";
		val METHOD_PUT = "PUT";
		val METHOD_TRACE = "TRACE";
		val HEADER_IFMODSINCE = "If-Modified-Since";
		val HEADER_LASTMOD = "Last-Modified";
		val LSTRING_FILE = "javax.servlet.http.LocalStrings";
	}


	open fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {

		var msg = "http.method_get_not_supported"
		if (req.http.endsWith("1.1")) {
			resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
		} else {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
		}
	}

	open fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
		var msg = "http.method_post_not_supported"
		if (req.http.endsWith("1.1")) {
			resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
		} else {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
		}
	}


	override open fun service(request: ServletRequest, responce: ServletResponse) {
		if (request is HttpServletRequest && responce is HttpServletResponse) {

			if (METHOD_POST == request.method) {
				doPost(request, responce)
			} else if (METHOD_GET == request.method) {
				doGet(request, responce)
			}

		}


	}


	override fun _init(config: ServletConfig?) {}

	override fun getServletConfig(): ServletConfig? = null


	override fun getServletInfo(): String? = null


	override fun destroy() {}


}